package com.bestvike.stone.spring.rabbit;

import com.bestvike.stone.core.lang.StringUtils;
import com.bestvike.stone.spring.context.TraceContext;
import com.bestvike.stone.spring.trace.rabbit.OutgoingLog;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;

import java.io.IOException;
import java.util.Map;

/**
 * Created by 许崇雷 on 2017-11-03.
 */
public final class RabbitTemplateEx extends RabbitTemplate {
    public RabbitTemplateEx(ConnectionFactory connectionFactory) {
        super(connectionFactory);
    }

    @Override
    protected void sendToRabbit(Channel channel, String exchange, String routingKey, boolean mandatory, Message message) throws IOException {
        TraceContext.beginSpan();
        MessageProperties properties = message.getMessageProperties();
        if (StringUtils.isEmpty(properties.getMessageId()))
            properties.setMessageId(TraceContext.getTraceSpanId());
        Map<String, Object> log = OutgoingLog.writeBeginLog(message, exchange, routingKey);
        long begin = System.currentTimeMillis();
        try {
            super.sendToRabbit(channel, exchange, routingKey, mandatory, message);
            OutgoingLog.writeEndLog(log, System.currentTimeMillis() - begin);
        } catch (Exception e) {
            OutgoingLog.writeErrorLog(log, e, System.currentTimeMillis() - begin);
            throw e;
        } finally {
            TraceContext.endSpan();
        }
    }
}
